const { BrowserWindow, screen, session, ipcMain } = require('electron')
const windowStateKeeper = require('electron-window-state')
const path = require('path')
const dc = require('./desktopCapturer') 

// 注入的JS
const storage = require('../executeJavaScript/storage')

function openWindow() {
  // 获取可视窗口的尺寸
  const {
    width: defaultWidth, 
    height: defaultHeight
  } = screen.getPrimaryDisplay().workAreaSize

  // 定义用户操作窗口的位置和尺寸的缓存对象
  const { x, y, width, height } = mainWindowState = windowStateKeeper({
    defaultWidth: 1000,
    defaultHeight: 800
  })

  // 创建一个窗口独享的session
  const customSess = session.fromPartition('persist:part1')

  // 创建一个窗口对象
  const win = new BrowserWindow({
    x,
    y,
    width,
    height,
    minHeight: 80,
    minWidth: 100,
    // fullscreen: true,
    webPreferences: {
      nativeWindowOpen: true,
      preload: path.resolve(__dirname, '../preload.js')
    },
    session: customSess
  })

  mainWindowState.manage(win)

  // 加载外部网站
  win.loadURL('http://localhost:8080')

  // 获取当前窗口的webcontents
  const wc = win.webContents

  // 打开开发者工具
  // wc.openDevTools()

  // 写入storage
  wc.executeJavaScript(storage.set())

  // 读取storages
  wc.executeJavaScript(storage.get()).then((result) => {
    // console.log(result)
  })

  // 监听渲染进程传送过来的url
  ipcMain.on('page-url', async (e, url) => {
    let result = await dc(url)
    wc.send('page-data', result)
  })
}

module.exports = openWindow